<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="90px"
    >
      <el-form-item label="模板名称" prop="name">
        <div v-if="formType === 'view'">{{ formData.name }}</div>
        <el-input v-model="formData.name" placeholder="请输入" class="gw-input-width-244" v-else />
      </el-form-item>
      <el-form-item label="描述" prop="remark">
        <div v-if="formType === 'view'">{{ formData.remark }}</div>
        <el-input
          v-model="formData.remark"
          :rows="6"
          type="textarea"
          placeholder="请输入内容"
          maxlength="300"
          show-word-limit
          v-else
        />
      </el-form-item>
    </el-form>
    <template #footer v-if="formType !== 'view'">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button @click="submitForm" type="primary">确定</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { PromptApi, PromptVO } from '@/api/multiModel/prompt'

/** prompt模板 表单 */
defineOptions({ name: 'PromptForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: undefined,
  remark: undefined,

})
const formRules = reactive({
  name: [{ required: true, message: '模板名称不能为空', trigger: 'blur' }],
  remark: [{ required: true, message: '描述不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type) + 'prompt模板'
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    try {
      formData.value = await PromptApi.getPrompt(id)
    } finally {
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  try {
    const data = formData.value as unknown as PromptVO
    if (formType.value === 'create') {
      await PromptApi.createPrompt(data)
      message.success(t('common.createSuccess'))
    } else {
      await PromptApi.updatePrompt(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    remark: undefined,
  }
  formRef.value?.resetFields()
}
</script>